# coding:utf-8
import requests
import re
from bs4 import BeautifulSoup

# 作者：上海-悠悠 QQ交流群：512200893

def getTokenCode(s):
    '''
        要从登录页面提取token，code， 然后在头信息里面添加
        <!-- 页面样式 --><!-- 动态token，防御伪造请求，重复提交 -->
        <script type="text/javascript">
            window.X_Anti_Forge_Token = 'dde4db4a-888e-47ca-8277-0c6da6a8fc19';
            window.X_Anti_Forge_Code = '61142241';
        </script>
    '''
    url = 'https://passport.lagou.com/login/login.html'
    h = {
         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
        }
    # 更新session的headers
    s.headers.update(h)
    data = s.get(url, verify=False)
    soup = BeautifulSoup(data.content, "html.parser", from_encoding='utf-8')
    tokenCode = {}
    try:
        t = soup.find_all('script')[1].get_text()
        print(t)
        tokenCode['X_Anti_Forge_Token'] = re.findall(r"Token = '(.+?)'", t)[0]
        tokenCode['X_Anti_Forge_Code'] = re.findall(r"Code = '(.+?)'", t)[0]
    except:
        print("获取token和code失败")
        tokenCode['X_Anti_Forge_Token'] = ""
        tokenCode['X_Anti_Forge_Code'] = ""
    return tokenCode